package com.sduept.nwld.dataserver.controller.daily;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;

import org.primefaces.PrimeFaces;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.springframework.beans.factory.annotation.Autowired;

import com.sduept.bigdata.document.entity.core.RecordAttachment;
import com.sduept.bigdata.document.core.CommonDocumentProperties;
import com.sduept.nwld.dataserver.manager.protection.SpecialReportManager;
import com.sduept.nwld.dataserver.model.daily.SpecialReport;
import com.sduept.nwld.dataserver.model.daily.UrlFile;
import com.sduept.utils.DateUtil;

@Named
@ViewScoped
public class SpecialReportController extends DailyReportAbstractController {

	private static final long serialVersionUID = 8570287046133801601L;
	@Autowired
	private SpecialReportManager srm;
	@Autowired
	private CommonDocumentProperties pros;
	private List<SpecialReport> report = new ArrayList<>();
	private SpecialReport selectReport = null;
	private SpecialReport created = null;
	private StreamedContent file;
	private boolean fileExist = false;
	private HashSet<String> repeatFileNames = new HashSet<>();
	private String repeatReportId = null;

	@PostConstruct
	private void init() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String start = format.format(queryDate1);
		String end = format.format(queryDate2);
		report = srm.getSpecialReport(start, end);
		for (int i = 0; i < report.size(); i++) {
			SpecialReport a = report.get(i);
			a.setFileNames(srm.findFileByOId(a.getId()));
			if (a.getFileSaveName() != null && !a.getFileSaveName().equals("")) {
				List<UrlFile> UrlFiles = srm.getUrlListByFileNames(a.getFileSaveName());
				a.setUrlNames(UrlFiles);
			}
		}
	}

	public void ReportRowSelect(SelectEvent event) {
		selectReport = (SpecialReport) event.getObject();
	}

	public void update() {
		if (selectReport != null) {
			srm.updateSpecialReport(selectReport);
			addSuccessMessage("保存成功");
		}
	}

	public void createReport() {
		created = new SpecialReport();
		created.setDay(new Date());
	}

	public void saveNew() {
		if (created != null) {
			created = srm.creatSpecialReport(created);
			report.add(0, created);
		}
		created = null;
		addSuccessMessage("保存成功");
	}

	public void deleteReport() {
		if (selectReport != null) {
			try {
				srm.deleteSpecialReport(selectReport);
				report.remove(selectReport);
				selectReport = null;
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			addErrorMessage("请选择一条数据进行删除");
		}
		addSuccessMessage("删除成功！");

	}

	public void resetQuery() {
		queryDate1 = null;
		queryDate2 = null;
		resetqueryDate();
		selectReport = null;
		created = null;
	}

	public void queryByTime() {
		if (queryDate1 == null) {
			queryDate1 = new Date(0);
		}
		if (queryDate2 == null) {
			queryDate2 = new Date();
		}
		queryDate2 = DateUtil.addDays(queryDate2, 1);
		queryDate2 = DateUtil.addSeconds(queryDate2, -1);

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String start = format.format(queryDate1);
		String end = format.format(queryDate2);
		report = srm.getSpecialReport(start, end);

		for (int i = 0; i < report.size(); i++) {
			SpecialReport a = report.get(i);
			a.setFileNames(srm.findFileByOId(a.getId()));
			if (a.getFileSaveName() != null && !a.getFileSaveName().equals("")) {
				List<UrlFile> UrlFiles = srm.getUrlListByFileNames(a.getFileSaveName());
				a.setUrlNames(UrlFiles);
			}
		}
		refreshQueryParamter();
		selectReport = null;
	}

	public void fileUploadReturn(String fileReportId) {
		repeatReportId = fileReportId;
		HashMap<String, Integer> fileNameMap = new HashMap<>();
		SpecialReport fileReport = srm.findReportById(fileReportId);
		List<RecordAttachment> files = srm.findFileByOId(fileReportId);
		for (RecordAttachment r : files) {
			String fileName = r.getDescription();
			Integer fm = fileNameMap.get(fileName);
			if (fm == null) {
				fileNameMap.put(fileName, 1);
			} else {
				fileNameMap.put(fileName, fm + 1);
			}
		}
		List<UrlFile> urls = srm.getUrlListByFileNames(fileReport.getFileSaveName());
		for (UrlFile r : urls) {
			String fileName = r.getName();
			Integer fm = fileNameMap.get(fileName);
			if (fm == null) {
				fileNameMap.put(fileName, 1);
			} else {
				fileNameMap.put(fileName, fm + 1);
			}
		}
		srm.updateSpecialReport(fileReport);
		repeatFileNames = new HashSet<>();
		for (Map.Entry<String, Integer> en : fileNameMap.entrySet()) {
			if (en.getValue() > 1) {
				repeatFileNames.add(en.getKey());
			}
		}
		if (repeatFileNames.size() > 0) {
			openRepeatDialog();
		} else {
			queryByTime();
		}
		selectReport = null;
	}

	public void openRepeatDialog() {
		
		PrimeFaces.current().ajax().update("form4:repeatDlg");
		PrimeFaces.current().executeScript("PF('repeatDlg').show();");
	}

	public void replaceFile() {
		// 拿到新的文件，找到重复的时间早的，踢出去。
		SpecialReport report = srm.findReportById(repeatReportId);
		List<RecordAttachment> currentFiles = srm.findFileByOId(repeatReportId);
		Iterator<RecordAttachment> fit = currentFiles.iterator();
		List<UrlFile> urls = srm.getUrlListByFileNames(report.getFileSaveName());
		Iterator<UrlFile> uit = urls.iterator();

		// 删掉时间早的重复的
		String lastName = null;
		while (fit.hasNext()) {
			RecordAttachment f = fit.next();
			if (lastName != null && lastName.equals(f.getDescription())) {
				removeFile(repeatReportId, f);
			} else {
				lastName = f.getDescription();
				uit = urls.iterator();
				while (uit.hasNext()) {
					if (lastName != null && lastName.equals(uit.next().getName())) {
						uit.remove();
					}
				}
			}
		}
		if (urls.size() > 0) {
			String fileSaveName = "";
			for (UrlFile uf : urls) {
				fileSaveName += uf.getName() + ";";
			}
			fileSaveName.substring(fileSaveName.length() - 1, fileSaveName.length());
			report.setFileSaveName(fileSaveName);
		} else {
			report.setFileSaveName(null);
		}
		srm.updateSpecialReport(report);
		queryByTime();
	}

	public void cancelReplaceFile() {
		// 按照时间排序，找到最早的留下。其他的删掉。如果url有，就把file删了。
		SpecialReport report = srm.findReportById(repeatReportId);
		List<RecordAttachment> currentFiles = srm.findFileByOId(repeatReportId);
		Iterator<RecordAttachment> fit = currentFiles.iterator();
		List<UrlFile> urls = srm.getUrlListByFileNames(report.getFileSaveName());
		Iterator<UrlFile> uit = urls.iterator();

		// 删掉时间晚的重复的
		String lastName = null;
		while (fit.hasNext()) {
			RecordAttachment f = fit.next();
			if (lastName != null && lastName.equals(f.getDescription())) {
				removeFile(repeatReportId, f);
			} else {
				lastName = f.getDescription();
				uit = urls.iterator();
				while (uit.hasNext()) {
					if (lastName != null && lastName.equals(uit.next().getName())) {
						srm.deleteFile(f.getId());
					}
				}
			}
		}
		queryByTime();
	}

	public void updateFile(String aid) {
		openUploadFileDialog(aid, pros.getDocumentPath());
	}

	public void removeFile(String aid, RecordAttachment record) {
		try {
			String removePath = pros.getDocumentPath() + record.getName();
			File f = new File(removePath);
			fileExist = f.exists();
			if (fileExist) {
				fileExist = false;
				f.delete();
			}
			srm.deleteFile(record.getId());
			queryByTime();
			addSuccessMessage("删除成功");
		} catch (Exception e) {
			e.printStackTrace();
			addErrorMessage("删除失败");
		}
		selectReport = null;
	}

	public void removeFile(SpecialReport report, String fileName) {
		String fileNames = report.getFileSaveName();
		if (fileNames.indexOf(",") != -1) {
			fileName = "," + fileName;
		}
		if (fileNames.indexOf(fileName) != -1) {
			fileNames = fileNames.replace(fileName, "");
			report.setFileSaveName(fileNames);
			srm.updateSpecialReport(report);
		}
		queryByTime();
	}

	public String cutString(String str) {
		return str.length() > 19 ? str.substring(0, 20) + "..." : str;
	}

	public String replaceWithBr(String str) {
		str = str.replaceAll("(\r\n|\r|\n|\n\r)", "<br/>");
		return str;
	}

	public void fileDownloadView(String id) {
		RecordAttachment recordAttachment = srm.findFileById(id);
		InputStream stream = null;
		file = null;
		try {
			stream = new FileInputStream(pros.getDocumentPath() + recordAttachment.getName());
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} finally {
			fileExist = stream != null;
		}
		HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance()
				.getExternalContext().getRequest();
		try {
			String agent = request.getHeader("User-Agent").toLowerCase();
			if (agent != null
					&& (agent.indexOf("msie") != -1 || (agent.indexOf("rv") != -1 && agent.indexOf("firefox") == -1))
					|| agent.indexOf("edge") != -1) {
				file = new DefaultStreamedContent(stream, "application/octet-stream", URLEncoder.encode(
						recordAttachment.getDescription(), "UTF-8"));
			} else {
				file = new DefaultStreamedContent(stream, "application/octet-stream", new String(
						recordAttachment.getDescription().getBytes("UTF-8"), "ISO8859-1"));
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} finally {
			if (file == null) {
				fileExist = false;
			}
		}
	}

	public List<SpecialReport> getReport() {
		return report;
	}

	public void setReport(List<SpecialReport> report) {
		this.report = report;
	}

	public SpecialReport getCreated() {
		return created;
	}

	public void setCreated(SpecialReport created) {
		this.created = created;
	}

	public StreamedContent getFile() {
		return file;
	}

	public void setFile(StreamedContent file) {
		this.file = file;
	}

	public HashSet<String> getRepeatFileNames() {
		return repeatFileNames;
	}

	public void setRepeatFileNames(HashSet<String> repeatFileNames) {
		this.repeatFileNames = repeatFileNames;
	}

	public SpecialReport getSelectReport() {
		return selectReport;
	}

	public void setSelectReport(SpecialReport selectReport) {
		this.selectReport = selectReport;
	}

	public String getRepeatReportId() {
		return repeatReportId;
	}

	public void setRepeatReportId(String repeatReportId) {
		this.repeatReportId = repeatReportId;
	}

	public boolean isFileExist() {
		return fileExist;
	}

	public void setFileExist(boolean fileExist) {
		this.fileExist = fileExist;
	}

}
